import 'dart:io';

import 'package:flutter/material.dart';
import 'package:test2/util/ImagePickUtil.dart';
import 'package:test2/util/widget.dart';

import '../util/platform.dart';

class ImagePickView extends StatefulWidget {
  const ImagePickView({
    super.key,
    required this.onPick,
    required this.title,
    this.imageProvider,
    this.enable,
    this.onScreenshot,
    this.showScreenshot = true,
  });

  final String title;
  final Function(File file) onPick;
  final ImageProvider? imageProvider;
  final bool? enable;
  final bool showScreenshot;
  final Function()? onScreenshot;

  @override
  State<ImagePickView> createState() => _ImagePickViewState();
}

class _ImagePickViewState extends State<ImagePickView> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      spacing: 6,
      children: [
        Text(widget.title, style: TextStyle(fontSize: 16)),
        BorderContainer(
          radius: 12,
          height: widget.imageProvider == null ? 200 : null,
          width: double.maxFinite,
          bgColor: Colors.white,
          child: widget.imageProvider == null
              ? Icon(Icons.image_outlined)
              : Image(
                  image: ResizeImage(widget.imageProvider!, width: 1920),
                  fit: BoxFit.cover,
                ),
        ),

        if (widget.enable ?? false)
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              IconButton(
                onPressed: () async {
                  List<File> files = ImagePickUtil.convert2File(
                    await ImagePickUtil.selectPic(1),
                  );
                  if (files.isEmpty) {
                    return;
                  }
                  widget.onPick(files[0]);
                },
                icon: Icon(Icons.add_photo_alternate),
              ),
              if (PlatformUtil.isDesktop() && widget.showScreenshot)
                IconButton(
                  onPressed: () async {
                    // 触发截图
                    if (widget.onScreenshot != null) {
                      widget.onScreenshot!();
                    }
                  },
                  icon: Icon(Icons.screenshot_monitor),
                ),
              if (Platform.isAndroid)
                IconButton(
                  onPressed: () async {
                    List<File> files = ImagePickUtil.convert2File(
                      await ImagePickUtil.takePic(),
                    );
                    if (files.isEmpty) {
                      return;
                    }
                    widget.onPick(files[0]);
                  },
                  icon: Icon(Icons.add_a_photo),
                ),
            ],
          ),
      ],
    );
  }
}
